/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package paquetevistas.compra;

import Seguridad.Controlador.controladorseguridad;
import controlador.almacen.controladoralmacen;
import controlador.compra.controladorcompra;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import modelos.Producto;
import modelos.Productoxproveedor;
import modelos.Proveedor;
import modelos.Usuario;
import paquetevistas.Escritorio;
import static paquetevistas.compra.BuscarCompra.validacion;

/**
 *
 * @author Jacklin
 */
public class BuscarProveedor extends javax.swing.JInternalFrame {

    /**
     * Creates new form BuscarProveedor
     */
    
    public static NuevoProveedor proveedor;
    public static Proveedor proveedoraeditar;
    public static List<Productoxproveedor> prodsxprov;
    public static Productoxproveedor prodxprov;
    public static ModificarProveedor proveedorEditar;
    public static ProductosProveedor productoxproveedor;
    SupplierTableModel mySupplierTableModel = new SupplierTableModel();
    public static controladorcompra mycontroladorcompra = new controladorcompra();
    public static controladoralmacen mycontroladoralmacen = new controladoralmacen();
    public static CargaMasivaProveedor cargamasivaproveedor;

    //Para el registro de Log
    public static Usuario usuario = lbj.LBJ.Login.usuario;
    public static controladorseguridad mycontroladorseguridad = new controladorseguridad();
    
    private void loadComponents() {
//        jComboBox2.removeAllItems();
        List<Producto> productos=  new ArrayList<Producto>();
        productos=mycontroladoralmacen.sacaproductos();
        for (int i=0; i < productos.size(); i++){
            if (productos.get(i).getEstado() == 1 && (productos.get(i).getTipoproducto().getIdtipoproducto() == 1 || productos.get(i).getTipoproducto().getIdtipoproducto() == 2)) {
               jComboBox2.addItem(productos.get(i).getNombre()); 
            }
        }
        jComboBox2.setSelectedIndex(0);
    }
    
    class SupplierTableModel extends AbstractTableModel {
        
        List<Proveedor> prov = new ArrayList<Proveedor>();
        
        public SupplierTableModel() {
            prov = mycontroladorcompra.sacaproveedores();
        }
        
        String[] titles = {"Código", "Razón Social", "Teléfono", "Correo"};
        
        public int getRowCount() {
            return prov.size();
        }

        public int getColumnCount() {
            return 4;
        }

        public Object getValueAt(int rowIndex, int columnIndex) {
            String res = null;
            Proveedor p = prov.get(rowIndex);
            
            switch(columnIndex){
                case 0:
                    res=""+p.getIdproveedor();
                    break;
                case 1:
                    res=""+p.getRazonsocial();
                    break;
                case 2: 
                    res=""+p.getTelefono();
                    break;
                case 3:
                    res=""+p.getCorreo();
                   break;
            }
            return res;
        }
        
         public String getColumnName(int col) {
            return titles[col];
        }
        
    }
    public BuscarProveedor() {
        initComponents();
        loadComponents();
        jTable1.setModel(mySupplierTableModel);
        refreshSupplierTable();
        
        mycontroladorseguridad.insertarlog(usuario, new Date(), "Consultar", "Proveedor", "Consultar Proveedor");
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLayeredPane1 = new javax.swing.JLayeredPane();
        jLayeredPane2 = new javax.swing.JLayeredPane();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jLayeredPane4 = new javax.swing.JLayeredPane();
        jLabel7 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jrazonSocial = new javax.swing.JTextField();
        jruc = new javax.swing.JTextField();
        jComboBox2 = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLayeredPane3 = new javax.swing.JLayeredPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jButton4 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();

        setClosable(true);
        setIconifiable(true);
        setTitle("Mantenimiento de Proveedores");

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/file plus.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jLayeredPane2.add(jButton1);
        jButton1.setBounds(10, 20, 63, 39);

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/search.png"))); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jLayeredPane2.add(jButton2);
        jButton2.setBounds(90, 20, 60, 40);

        jLabel1.setText("Agregar");
        jLayeredPane2.add(jLabel1);
        jLabel1.setBounds(20, 60, 50, 14);

        jLabel2.setText("Buscar");
        jLayeredPane2.add(jLabel2);
        jLabel2.setBounds(100, 60, 50, 14);

        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/upload.png"))); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jLayeredPane2.add(jButton3);
        jButton3.setBounds(170, 20, 60, 40);

        jLabel3.setText("Carga Masiva");
        jLayeredPane2.add(jLabel3);
        jLabel3.setBounds(170, 60, 80, 14);

        jLayeredPane4.setBorder(javax.swing.BorderFactory.createTitledBorder("Criterios de Búsqueda"));

        jLabel7.setText("Razón Social:");
        jLayeredPane4.add(jLabel7);
        jLabel7.setBounds(40, 30, 140, 14);

        jLabel13.setText("Ruc:");
        jLayeredPane4.add(jLabel13);
        jLabel13.setBounds(40, 60, 130, 20);

        jrazonSocial.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrazonSocialActionPerformed(evt);
            }
        });
        jLayeredPane4.add(jrazonSocial);
        jrazonSocial.setBounds(220, 20, 140, 20);
        jLayeredPane4.add(jruc);
        jruc.setBounds(220, 60, 140, 20);

        jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Eliga un producto" }));
        jComboBox2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox2ActionPerformed(evt);
            }
        });
        jLayeredPane4.add(jComboBox2);
        jComboBox2.setBounds(220, 90, 140, 30);

        jLabel5.setText("Producto:");
        jLayeredPane4.add(jLabel5);
        jLabel5.setBounds(40, 100, 130, 20);

        jLabel6.setText("Estado:");
        jLayeredPane4.add(jLabel6);
        jLabel6.setBounds(40, 130, 140, 20);

        jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Activo", "Inactivo" }));
        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });
        jLayeredPane4.add(jComboBox1);
        jComboBox1.setBounds(220, 130, 140, 30);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Código", "Razón Social", "Teléfono", "Correo"
            }
        ));
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLayeredPane3.add(jScrollPane1);
        jScrollPane1.setBounds(20, 10, 390, 109);

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/search.png"))); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jLayeredPane3.add(jButton4);
        jButton4.setBounds(420, 40, 60, 40);

        jLabel4.setText("Producto");
        jLayeredPane3.add(jLabel4);
        jLabel4.setBounds(430, 80, 80, 14);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLayeredPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 458, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(30, 30, 30)
                        .addComponent(jLayeredPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 501, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(44, 44, 44)
                        .addComponent(jLayeredPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 453, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLayeredPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLayeredPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 187, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLayeredPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if(proveedor == null || proveedor.isClosed()){
            proveedor = new NuevoProveedor();
            Escritorio.proveedor.getDesktopPane().add(proveedor);
            proveedor.setVisible(true);
        }else
            try{
                proveedor.setSelected(true);
            }catch(Exception e){} 
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        Long ruc;
        String razonSocial=jrazonSocial.getText();
        if((jruc.getText().isEmpty())){
            ruc=0L;
        }else if(!validacion.es_numero_entero(jruc.getText())){
                ruc=-1L;
            }else{
          ruc= Long.parseLong(jruc.getText());  
          Long limitinf=9999999999L;
          Long limitsup=100000000000L;
          if((ruc.compareTo(limitinf)<0)||(ruc.compareTo(limitsup)>0)){
              ruc=-1L;
          }
        }       
//        System.out.println(jComboBox2.getSelectedItem().toString());
        String producto=jComboBox2.getSelectedItem().toString();
        String estado=jComboBox1.getSelectedItem().toString();
        mySupplierTableModel.prov = mycontroladorcompra.buscaproveedores(razonSocial, ruc, producto, estado);
        mySupplierTableModel.fireTableChanged(null);
        
        mycontroladorseguridad.insertarlog(usuario, new Date(), "Consultar", "Proveedor", "Consultar Proveedor");
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jrazonSocialActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrazonSocialActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jrazonSocialActionPerformed

    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox1ActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
        // TODO add your handling code here:
//        if (proveedorModificar == null || proveedorModificar.isClosed()) {
//            proveedorModificar = new ModificarProveedor();
//            getDesktopPane().add(proveedorModificar);
//            proveedorModificar.setVisible(true);
//        } else 
//            try {
//                proveedorModificar.setSelected(true);
//            } catch (Exception e) {}
        
        if (evt.getClickCount() == 2) {
            int row = jTable1.getSelectedRow();
            String ids = jTable1.getValueAt(row, 0).toString();
            int id = Integer.parseInt(ids);
            proveedoraeditar = mycontroladorcompra.sacaproveedorbyid(id);
            proveedorEditar = new ModificarProveedor();
            Escritorio.proveedor.getDesktopPane().add(proveedorEditar);
            proveedorEditar.setVisible(true);
        }
        
    }//GEN-LAST:event_jTable1MouseClicked

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
//        if(proveedorProducto == null || proveedorProducto.isClosed()){
//            proveedorProducto = new ProductosProveedor();
//            Escritorio.proveedor.getDesktopPane().add(proveedorProducto);
//            proveedorProducto.setVisible(true);
//        }else
//            try{
//                proveedorProducto.setSelected(true);
//            }catch(Exception e){} 
        int row = jTable1.getSelectedRow();
        if(row>=0){
            String ids = jTable1.getValueAt(row, 0).toString();
        Integer id = Integer.parseInt(ids);
        prodsxprov = mycontroladorcompra.sacaprodxprovbyid(id);//investigar
        productoxproveedor = new ProductosProveedor();
        Escritorio.proveedor.getDesktopPane().add(productoxproveedor);
        productoxproveedor.setVisible(true);
        }else{
           JOptionPane.showMessageDialog(null, "Debe seleccionar una fila de la tabla"); 
        }
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jComboBox2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox2ActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jComboBox2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        if (cargamasivaproveedor == null || cargamasivaproveedor.isClosed()) {
            cargamasivaproveedor = new CargaMasivaProveedor();
            Escritorio.proveedor.getDesktopPane().add(cargamasivaproveedor);
            cargamasivaproveedor.setVisible(true);
        } else {
            try {
                cargamasivaproveedor.setSelected(true);
            } catch (Exception e) {
            }
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLayeredPane jLayeredPane1;
    private javax.swing.JLayeredPane jLayeredPane2;
    private javax.swing.JLayeredPane jLayeredPane3;
    private javax.swing.JLayeredPane jLayeredPane4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jrazonSocial;
    private javax.swing.JTextField jruc;
    // End of variables declaration//GEN-END:variables

    void refreshSupplierTable() {
        mySupplierTableModel.prov = mycontroladorcompra.sacaproveedores();
        mySupplierTableModel.fireTableChanged(null);
    }

}
